"""
Copyright (c) 2023 - present SKbioinfo
"""

from flask_restful import reqparse,Resource
from flask import jsonify,request
from flask_login import login_required,current_user

from apps.NGS_API.record.interface_operate_his import parse_reason
from apps.NGS_API.common.db_table_config import *
from apps.NGS_API.common.common_generate_id import *
from apps.NGS_API.utils.log_helper import lg
from apps.NGS_API.bioana.db_bioana import *
from apps.NGS_API.connector.db_common import *

from apps.NGS_API.record.history_util import *
pm=operation_monitor(table_name=ngs_op_log["name"])

'''
    Bioanalysis infos API
'''
class interfaceBioana(Resource):
    @login_required
    def get(self):
        try:
            bioana={}
            bioana["recent_ana"]="暂无分析"
            bioana_infos=[]
            ### receive bioana base infos from database ###
            bioana_base_info=get_bioana_info()
            ### collect bioana base info ###
            if len(bioana_base_info) == 0:
                pass
            else:
                for analysis in bioana_base_info:
                    bioana_infos.append({
                        "id": analysis[14],
                        "ana_id": analysis[0],
                        "proj_id": analysis[1],
                        "n_sam": analysis[2],
                        "op_user": analysis[3],
                        "ch_user": analysis[4],
                        "status": analysis[5],
                        "pipeline": analysis[6],
                        "com_hash": analysis[7],
                        "op_st_time": analysis[8],
                        "op_ed_time": analysis[9],
                        "ex_argument": analysis[10],
                        "cre_time": analysis[11],
                        "md_time": analysis[12],
                        "arg_temp": analysis[13],
                        "flag": False,
                        "link": '''<a href=\"/reports/{report_id}\" class=\"d-block\">
                            报告链接
                            </a>'''.format(report_id="mg0402")
                    })
      
                ### recent bio analysis ###
                pipe_names={
                    "SK_mag":"外源因子检测"
                }
                bioana["recent_ana"]=bioana_base_info[0][6]
            bioana["bioana_infos"]=bioana_infos
            response=jsonify(bioana)
            response.status=202
            return response
        except Exception as e:
            lg.error(e)

class interfaceBioanaID(Resource):
    @login_required
    def delete(self,id):
        try:
            if request.data.decode(encoding='UTF-8',errors='strict') == "-1":
                pass
            else:
                ### SQL: record reason details ###
                reason_details=parse_reason(data=request.json)
                ### SQL: record user operation ###
                record_user_operate(
                    pm=pm,
                    current_user=current_user,
                    record_table=ngs_op_log["name"],
                    resource_table=bioana_db["name"],
                    ch_user=current_user,
                    type_name="delete",
                    cols='''
                        analysis_id
                    ''',
                    id=id,
                    reason_details=reason_details
                )
                ### SQL: delete bioanalysis infos ###
                delete_sql='''DELETE FROM {table_name} WHERE {db_name}={col_value}'''.format(
                    table_name=bioana_db["name"],
                    col_value=id,
                    db_name="id"
                )
                ### SQL: delete infos ###
                delete_info(delete_sql=delete_sql)
                return id
        except Exception as e:
            lg.error(e)
            
    @login_required        
    def post(self,id):
        try:
            parser=reqparse.RequestParser()
            ### SQL: record user operation ###
            ### SQL: record reason details ###
            # reason_details=parse_reason(data=request.json)
            record_user_operate(
                pm=pm,
                current_user=current_user,
                record_table=ngs_op_log["name"],
                resource_table=bioana_db["name"],
                ch_user=current_user,
                type_name="delete",
                cols='''
                    analysis_id
                ''',
                id=id,
                reason_details=""
            )
            ### SQL: delete bioanalysis infos ###
            delete_sql="DELETE FROM {table_name} WHERE {db_name} =\"{col_value}\"".format(
                table_name=bioana_db["name"],
                col_value=id,
                db_name="id"
            )
            delete_info(delete_sql=delete_sql)
        except Exception as e:
            lg.error(e)
            
    @login_required
    def put(self,id):
        try:
            parser=reqparse.RequestParser()
            # parser.add_argument("proj_id",type=str,required=True,help="项目编号输入有误！")
            parser.add_argument("ana_id",type=str,required=True,help="项目名称输入有误！")
            parser.add_argument("arg_temp",type=str,required=True,help="模板输入有误！")
            parser.add_argument("com_hash",type=str,required=True,help="客户ID输入有误！")
            parser.add_argument("cre_time",type=str,required=True,help="产品编号输入有误！")
            parser.add_argument("ex_argument",type=str,required=True,help="平台编号输入有误！")
            parser.add_argument("n_sam",type=int,required=True,help="项目状态输入有误！")
            # parser.add_argument("op_st_time",type=str,required=True,help="样品接收编号输入有误！")
            # parser.add_argument("op_ed_time",type=str,required=True,help="样品接收编号输入有误！")
            parser.add_argument("op_user",type=str,required=True,help="操作人输入有误！")
            parser.add_argument("ch_user",type=str,required=True,help="项目类型输入有误！")
            parser.add_argument("pipeline",type=str,required=True,help="流程输入有误！")
            parser.add_argument("status",type=str,required=True,help="样品状态输入有误！")
            # parser.add_argument("md_time",type=str,required=True,help="样品状态输入有误！")
            args=parser.parse_args()
            ### SQL: update bioana database ###
            update_bioana_sql='''
                UPDATE 
                    {table_name}
                SET 
                    # project_id=\"{proj_id}\",
                    analysis_id=\"{ana_id}\",
                    argument_template=\"{arg_temp}\",
                    commit_hash=\"{com_hash}\",
                    # create_time=\"{cre_time}\",
                    extra_argument=\"{ex_argument}\",
                    n_sample={n_sam},
                    operate_user=\"{op_user}\",
                    check_user=\"{ch_user}\",
                    pipeline=\"{pipeline}\",
                    status={status},
                    modify_time=\"{md_time}\"
                WHERE id={id}
            '''.format(
                    table_name=bioana_db["name"],
                    # proj_id=args.get("proj_id"),
                    ana_id=args.get("ana_id"),
                    arg_temp=args.get("arg_temp"),
                    com_hash=args.get("com_hash"),
                    cre_time=args.get("cre_time"),
                    ex_argument=args.get("ex_argument"),
                    n_sam=args.get("n_sam"),
                    op_user=args.get("op_user"),
                    ch_user=args.get("ch_user"),
                    pipeline=args.get("pipeline"),
                    status=args.get("status"),
                    md_time=get_current_time(),
                    id=id
            )
            ### SQL: update bioana infos ###
            update_info(update_bioana_sql)
        except Exception as e:
            lg.error(e)
            
class interfaceBioanaList(Resource):
    @login_required
    def get(self):
        ### SQL: query bioana list ###
        cols='''
            tb1.id,
            tb1.project_id,
            tb1.sample_id,
            tb2.library_id 
        '''
        bioana_list_query='''
            SELECT 
                {cols}
            FROM {table_one} as tb1
            LEFT JOIN {table_two} as tb2
            ON tb1.sample_id=tb2.sample_id
        '''.format(
            cols=cols,
            table_one=sample_db["name"],
            table_two=ngsLib_db["name"]
        )
        bioana_infos=dic_query_info(bioana_list_query)
        biolist=[]
        if len(bioana_infos) == 0:
            pass
        else:
            for bio in bioana_infos:
                biolist.append({
                    "id":bio["id"],
                    "project_id":bio["project_id"],
                    "sample_id":bio["sample_id"],
                    "library_id":bio["library_id"]
                })
        response=jsonify(biolist)
        response.status=202
        return response
    def get_infos(self):
        ### SQL: query bioana list ###
        cols='''
            tb1.id,
            tb1.project_id,
            tb1.sample_id,
            tb2.library_id 
        '''
        bioana_list_query='''
            SELECT 
                {cols}
            FROM {table_one} as tb1
            LEFT JOIN {table_two} as tb2
            ON tb1.sample_id=tb2.sample_id
        '''.format(
            cols=cols,
            table_one=sample_db["name"],
            table_two=ngsLib_db["name"]
        )
        bioana_infos=dic_query_info(bioana_list_query)
        biolist=[]
        if len(bioana_infos) == 0:
            pass
        else:
            for bio in bioana_infos:
                biolist.append({
                    "id":bio["id"],
                    "project_id":bio["project_id"],
                    "sample_id":bio["sample_id"],
                    "library_id":bio["library_id"]
                })
        return biolist
    @login_required
    def post(self):
        try:
            parser=reqparse.RequestParser()
            parser.add_argument("lib_id",type=str,required=True,help="文库编号输入错误！")
            parser.add_argument("n_sam",type=int,required=True,help="样品数输入有误！")
            parser.add_argument("ana_id",type=str,required=True,help="分析编号输入有误！")
            parser.add_argument("pipe",type=str,required=True,help="流程名称输入有误！")
            parser.add_argument("com_hash",type=str,required=True,help="commit版本输入错误！")
            parser.add_argument("arg_temp",type=str,required=True,help="模板输入有误！")
            parser.add_argument("op_user",type=str,required=True,help="操作人输入有误！")
            parser.add_argument("ch_user",type=str,required=True,help="审核人输入有误！")
            args=parser.parse_args()
            ### SQL: add library to database ###
            cols='''
                analysis_id,
                pipeline,
                n_sample,
                operate_user,
                check_user,
                status,
                commit_hash,
                operate_start_time,
                operate_end_time,
                argument_template,
                extra_argument,
                create_time,
                modify_time
            '''
            values='''
                \"{ana_id}\",
                \"{pipe}\",
                {n_sam},
                \"{op_user}\",
                \"{ch_user}\",
                {status},
                \"{commit_hash}\",
                \"{op_start_time}\",
                \"{op_end_time}\",
                \"{arg_temp}\",
                \"{ext_arg}\",
                \"{cre_time}\",
                \"{md_time}\"
            '''.format(
                ana_id=args.get("ana_id"),
                pipe=args.get("pipe"),
                n_sam=args.get("n_sam"),
                op_user=args.get("op_user"),
                ch_user=args.get("ch_user"),
                status=0,
                commit_hash=args.get("com_hash"),
                op_start_time=get_current_time(),
                op_end_time=get_current_time(),
                arg_temp=args.get("arg_temp"),
                ext_arg="",
                cre_time=get_current_time(),
                md_time=get_current_time()
            )
            insert_lib_sql='''
                INSERT INTO {table_name}
                ({cols}) VALUES (
                    {values}
                )
            '''.format(
                table_name=bioana_db["name"],
                cols=cols,
                values=values
            )
            ### SQL: library info add ###
            add_info(insert_lib_sql)
            ### SQL: insert relationship between library & bioana ###
            for lib in args.get("lib_id").split(","):
                insert_lib_sql = '''
                    INSERT INTO {table_name}
                    (library_id,analysis_id)VALUES(
                        \"{library_id}\",\"{analysis_id}\"
                    )
                '''.format(
                    table_name=bioana_rel_db["name"],
                    library_id=lib,
                    analysis_id=args.get("ana_id")
                )
                add_info(insert_lib_sql)
            return 202
        except Exception as e:
            lg.error(e)
            return 505
class interfacegenerateBioanaid(Resource):
    @login_required
    def get(self):
        col="analysis_id"
        ana_gen=id_generator(name=bioana_db["name"])
        ana_id=ana_gen.generate_id(col=col)
        ana_prefix=ana_gen.generate_prefix(tag="bioana")
        return {"id":ana_id[col],"prefix":ana_prefix}
    
    
        
  